<template>
    <div>
        <!-- <searchForm :searchArr="searchArr" @onSubmit="onSubmit">
            <template #sbuName="{ item }">
                <el-select
                    v-model="item.value"
                    placeholder="请选择"
                    style="width: 100%"
                    :clearable="true"
                    filterable
                    remote
                    :remote-method="getSbuData"
                >
                    <el-option
                        v-for="item in sbuOptions"
                        :key="item.sbuName"
                        :label="item.sbuName"
                        :value="item.sbuName"
                    />
                </el-select>
            </template>
        </searchForm> -->
        <div class="gva-table-box">
            <LTable
                tableName="productSpec"
                :pages="pages"
                :columns="columns"
                :tableData="tableData"
                :maxHeight="'calc(100vh - 226px)'"
                :searchArr="searchArr"
                :isSearch="true"
                @onSubmit="onSubmit"
                @updateMultipleSelection="updateMultipleSelection"
                @changePages="changePages"
                @rowDblclick="
                    (v) => {
                        getDetails(v, 'v');
                    }
                "
                :export="true"
            >
                <template #action>
                    <div class="gva-btn-list" v-if="userStore.userInfo.authority?.authorityId !== 1000">
                        <el-button
                            type="primary"
                            icon="plus"
                            @click="openDialog"
                            >新增</el-button
                        >
                        <el-button
                            icon="delete"
                            v-auth="btnAuth.batchDel"
                            style="margin-left: 10px"
                            :disabled="!multipleSelection.length"
                            @click="onDelete"
                            >删除</el-button
                        >
                        <!-- <el-button
                            :disabled="multipleSelection.length!=1"
                            type="primary"
                            icon="edit"
                            class="table-button"
                            @click="getDetails(multipleSelection.length==1&&multipleSelection[0])"
                        >
                            编辑
                        </el-button> -->
                        <el-button
                            type="primary"
                            class="table-button"
                            :disabled="multipleSelection.length != 1"
                            @click="historyVision"
                        >
                            历史版本
                        </el-button>

                        <relatedBtn
                            :disabled="multipleSelection.length != 1"
                            :row="
                                multipleSelection.length == 1 &&
                                multipleSelection[0]
                            "
                            :modalType="'productSpec'"
                        />

                        <el-button
                            type="primary"
                            icon="DocumentCopy"
                            class="table-button"
                            :disabled="multipleSelection.length!=1"
                            @click="copySpecificationFun(multipleSelection.length==1&&multipleSelection[0])"
                            >复制</el-button
                        >
                    </div>
                </template>
                <!-- <template #styleNum="scope">
                    <el-popover placement="right" :width="80" trigger="hover">
                        <template #reference>
                            {{ scope.row.styleNum }}
                        </template>
                        <div class="m-action-btns">
                            <el-button
                                type="primary"
                                link
                                icon="edit"
                                class="table-button"
                                @click="getDetails(scope.row)"
                                >编辑</el-button
                            >
                            <el-button
                                type="primary"
                                link
                                icon="delete"
                                @click="deleteRow(scope.row)"
                                >删除</el-button
                            >
                            <relatedBtn
                                :row="scope.row"
                                :modalType="'productSpec'"
                            />
                            <el-button
                                type="primary"
                                link
                                icon="DocumentCopy"
                                class="table-button"
                                @click="copySpecificationFun(scope.row)"
                                >复制</el-button
                            >
                            <el-button
                                type="primary"
                                link
                                icon="discount"
                                class="table-button"
                                @click="detailSbuProjectsFunc(scope.row)"
                                >历史快照</el-button
                            >
                            <el-button
                                type="primary"
                                link
                                icon="discount"
                                class="table-button"
                                >历史版本</el-button
                            >
                            
                        </div>
                    </el-popover>
                </template> -->
                <template #CreatedAt="{ row }">
                    {{ formatDate(row.CreatedAt) }}
                </template>
                <template #UpdatedAt="{ row }">
                    {{ formatDate(row.UpdatedAt) }}
                </template>
            
                  <template #FirstCreatedAt="{ row }">
                    <span v-if="row.FirstCreatedAt">{{formatDate(row.FirstCreatedAt)=="1-01-01" ? '' : formatDate(row.FirstCreatedAt) }}</span>
                </template>
                <!-- <template #status="{ row }">
                    {{ row.status == "0" ? "草稿" : "已確認" }}
                </template> -->
                <!-- <template #event>
                    <el-table-column
                        align="left"
                        label="操作"
                        fixed="right"
                        min-width="480"
                        width="480"
                    >
                        <template #default="scope">
                            <el-button
                                type="primary"
                                link
                                icon="edit"
                                class="table-button"
                                @click="getDetails(scope.row)"
                                >编辑</el-button
                            >
                            <el-button
                                type="primary"
                                link
                                icon="delete"
                                @click="deleteRow(scope.row)"
                                >删除</el-button
                            >
                            <relatedBtn
                                :row="scope.row"
                                :modalType="'productSpec'"
                            />
                            <el-button
                                type="primary"
                                link
                                icon="discount"
                                class="table-button"
                                @click="detailSbuProjectsFunc(scope.row)"
                                >历史快照</el-button
                            >
                            <el-button
                                type="primary"
                                link
                                icon="discount"
                                class="table-button"
                                >历史版本</el-button
                            >
                            <el-button
                                type="primary"
                                link
                                icon="DocumentCopy"
                                class="table-button"
                                @click="copySpecificationShow = true"
                                >复制</el-button
                            >
                        </template>
                    </el-table-column>
                </template> -->
            </LTable>
        </div>
        <!-- 复制 -->
        <el-dialog
            v-model="copySpecificationShow"
            destroy-on-close
            title="复制产品规格"
            width="450"
        >
            <div class="import-part">
                <!-- <el-table
                    :data="copySpecificationList"
                    ref="copySpecificationListRef"
                    style="width: 100%"
                    border
                >
                    <el-table-column prop="num" label="款式编号">
                        <template #default="{ row }">
                            <el-select
                                v-model="toStyleNum"
                                placeholder="请选择"
                                style="width: 100%"
                                filterable
                                remote
                                :remote-method="remoteMethodProjectStyles"
                            >
                                <el-option
                                    v-for="item in productStylesList"
                                    :key="item.styleNum"
                                    :label="item.styleNum"
                                    :value="item.styleNum"
                                />
                            </el-select>
                        </template>
                    </el-table-column>
                </el-table> -->
                <input
                    v-model="toStyleNum"
                    :clearable="true"
                    @input="handleInput"
                    placeholder="请填写款式编号"
                />
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="replicateProductSpecFun">
                        确定
                    </el-button>
                    <el-button @click="copySpecificationShow = false">
                        关闭
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="historyVisionShow" title="历史版本" width="900">
            <el-table
                ref="multipleTableRef"
                :data="historyList"
                :row-class-name="tableRowClassName"
                @rowDblclick="rowDblclickFun"
                style="width: 100%"
            >
                <el-table-column prop="styleNum" label="款式编号" />
                <el-table-column prop="localStyleNum" label="本厂款号" />
                <el-table-column prop="cumstomerNum" label="客户款号" />
                <el-table-column prop="version" label="版本" />
                <el-table-column prop="createdAt" label="创建时间">
                    <template #default="scope">
                        <span>
                            {{ formatDate(scope.row.CreatedAt) }}
                        </span>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script setup>
import {
    createProductSpec,
    deleteProductSpec,
    deleteProductSpecByIds,
    updateProductSpec,
    findProductSpec,
    getProductSpecList,
    replicateProductSpec,
    getProductSpecHistoryList,
} from "@/api/plmProductSpec";
import { getSbuDataList } from "@/api/confSbuData";
import { useRoute, useRouter } from "vue-router";
// 全量引入格式化工具 请按需保留
import {
    getDictFunc,
    formatDate,
    formatBoolean,
    filterDict,
    ReturnArrImg,
    onDownloadFile,
} from "@/utils/format";
import { getProductStylesQuickList } from "@/api/plmProductStyles";
import { useDict } from "@/utils/dictionary.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/pinia/modules/user";
import { ref, reactive, computed, onMounted, onActivated, watch } from "vue";
// 引入组件
import LTable from "@/components/LTable/LTable.vue";
// import searchForm from "@/components/searchForm/searchForm.vue";
defineOptions({
    name: "ProductSpec",
});
import { useBtnAuth } from "@/utils/btnAuth";
const btnAuth = useBtnAuth();

// 使用 useRoute 函数获取当前路由信息
const router = new useRouter();
const route = new useRoute();
const userStore = useUserStore();
const CreatedAtFilters = computed(() => {
    return tableData.value.map((item) => {
        return { text: formatDate(item.CreatedAt), value: item.CreatedAt };
    });
});
const UpdatedAtFilters = computed(() => {
    return tableData.value.map((item) => {
        return { text: formatDate(item.UpdatedAt), value: item.UpdatedAt };
    });
});
// [
//     {
//         prop: "CreatedAt",
//         label: "创建日期",
//         width: 200,
//         show: true,
//         filter: true,
//         slot: "CreatedAt",
//         tableColumnProps: {
//             sortable: true,
//             filters: CreatedAtFilters,
//             "filter-method": function filterHandler(value, row, column) {
//                 const property = column["property"];
//                 return row[property] === value;
//             },
//         },
//     },
//     {
//         prop: "UpdatedAt",
//         label: "更新时间",
//         width: 200,
//         show: true,
//         filter: true,
//         slot: "UpdatedAt",
//         tableColumnProps: {
//             sortable: true,
//             filters: UpdatedAtFilters,
//             "filter-method": function filterHandler(value, row, column) {
//                 const property = column["property"];
//                 return row[property] === value;
//             },
//         },
//     },
// ];

// =========== 表格控制部分 ===========

const tableData = ref([]);
const searchInfo = ref({});
const pages = ref({
    page: 1,
    pageSize: 20,
    total: 0,
});
// ======表格头部数据======
const columns = ref([
    {
        prop: "styleNum",
        label: "款式编号",
        fixedWidth: 130,
        show: true,
        isSearch: true,
        filter: true,
        // slot: "styleNum",
        tableColumnProps: {
            fixed: "left",
        },
    },
    {
        prop: "sbuNum",
        label: "SBU",
        fixedWidth: 100,
        show: true,
        isSearch: true,
        filter: true,
    },
    {
        prop: "cumstomerNum",
        label: "客户编号",
        fixedWidth: 130,
        show: true,
        isSearch: true,
        filter: true,
    },
    {
        prop: "customerBrand",
        label: "品牌",
        fixedWidth: 130,
        show: true,
        isSearch: true,
        filter: true,
    },
    {
        prop: "localStyleNum",
        label: "本厂款号",
        fixedWidth: 160,
        show: true,
        isSearch: true,
        filter: true,
    },
    {
        prop: "status",
        fixedWidth: 90,
        label: "状态",
        show: true,
        // slot: "status",
    },
    {
        prop: "customerStyleNum",
        label: "客户款号",
        fixedWidth: 120,
        show: true,
        isSearch: true,
        filter: true,
    },
    {
        prop: "frameMaterials",
        label: "镜架材质",
        fixedWidth: 120,
        show: true,
        isSearch: true,
        filter: true,
    },
    // {
    //     prop: "glassFrameCate",
    //     label: "镜架类别",
    //     fixedWidth: 120,
    //     show: true,
    //     isSearch:true,
    //     filter: true,
    // },
    {
        prop: "sheetArcBend",
        fixedWidth: 150,
        label: "片弧弯",
        show: true,
    },
    {
        prop: "localTiltAngle",
        fixedWidth: 130,
        label: "本厂架倾角(度)",
        show: true,
    },
    {
        prop: "version",
        fixedWidth: 100,
        label: "版本",
        show: true,
    },
    {
        prop: "CreatedAt",
        label: "创建时间",
        fixedWidth: 130,
        show: true,
        isSearch: true,
        filter: true,
        // tableColumnProps: {
        //     formatter: (row) => formatDate(row.CreatedAt),
        // },
    },
    {
        prop: "createUser",
        label: "创建人",
        fixedWidth: 100,
        show: true,
        isSearch: true,
        filter: true,
    },
    {
        prop: "UpdatedAt",
        label: "更新时间",
        fixedWidth: 130,
        show: true,
        isSearch: true,
        filter: true,
        tableColumnProps: {
            formatter: (row) => formatDate(row.UpdatedAt),
        },
    },
    {
        prop: "updateUser",
        label: "更新人",
        fixedWidth: 100,
        show: true,
        isSearch: true,
        filter: true,
    },
    {
        prop: "FirstCreatedAt",
        label:'第一版本创建时间',
        show: true,
        isSearch: true,
        // filter: true,
        fixedWidth: 150,
           tableColumnProps: {
            formatter: (row) => formatDate(row.FirstCreatedAt)=="1-01-01" ? "" :formatDate(row.FirstCreatedAt) ,
        },
            // slot:"FirstCreatedAt"
    },
      
]);
// ======查询数据======
const searchArr = ref([
    {
        prop: "styleNum",
        label: "款式编号",
        show: true, // 通过 show 来控制列的展示或隐藏
        value: "",
        type: "input",
    },
    {
        prop: "sbuNum",
        label: "SBU",
        show: true,
        value: "",
        type: "input",
        slot: "sbuName",
    },
    {
        prop: "cumstomerNum",
        label: "客户编号",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "customerBrand",
        label: "品牌",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "customerStyleNum",
        label: "客户款号",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "localStyleNum",
        label: "本厂款号",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "frameMaterials",
        label: "镜架材质",
        show: true,
        value: undefined,
        type: "select",
        selectList: [],
    },
    // {
    //     prop: "glassFrameCate",
    //     label: "镜架类别",
    //     show: true,
    //     value: undefined,
    //     type: "select",
    //     selectList: [],
    // },
    {
        prop: "sheetArcBend",
        label: "片弧弯",
        show: true,
        value: undefined,
        type: "select",
        selectList: [],
    },
    {
        prop: "localTiltAngle",
        label: "本厂架倾角(度)",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "status",
        label: "状态",
        show: true,
        value: undefined,
        type: "select",
        selectList: [
            { label: "草稿", value: "0" },
            { label: "已確認", value: "1" },
        ],
    },
    {
        prop: "CreatedAt",
        label: "创建时间",
        show: true,
        value: "",
        type: "datetimerange",
    },
    {
        prop: "createUser",
        label: "创建人",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "UpdatedAt",
        label: "更新时间",
        show: true,
        value: "",
        type: "datetimerange",
    },
    {
        prop: "updateUser",
        label: "更新人",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "version",
        label: "版本",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "FirstCreatedAt",
        label:'第一版本创建时间',
        show: true,
        value: "",
        type: "datetimerange",
    },
]);

// 复制产品规格
const copySpecificationShow = ref(false);
const copySpecificationList = ref([{}]);
const projectList = ref([]);
const styleList = ref([]);

const addCopyItem = () => {
    copySpecificationList.value.push({});
};
const delCopyItem = (index) => {
    copySpecificationList.value.splice(index, 1);
};

// 搜索
const onSubmit = (val) => {
    searchInfo.value = {
        ...val,
    };
    // if (searchInfo.value.CreatedAt) {
    //     searchInfo.value["startCreatedAt"] =
    //         searchInfo.value.CreatedAt[0] || "";
    //     searchInfo.value["endCreatedAt"] = searchInfo.value.CreatedAt[1] || "";
    // }
    // if (searchInfo.value.UpdatedAt) {
    //     searchInfo.value["startUpdatedAt"] =
    //         searchInfo.value.UpdatedAt[0] || "";
    //     searchInfo.value["endUpdatedAt"] = searchInfo.value.UpdatedAt[1] || "";
    // }
    pages.value.page = 1;
    pages.value.pageSize = 20;
    getTableData();
};

// 改变页码
function changePages(currentPages) {
    pages.value = {
        ...pages.value,
        ...currentPages,
    };
    getTableData();
}

// 查询
const getTableData = async () => {
    const table = await getProductSpecList({
        page: pages.value.page,
        pageSize: pages.value.pageSize,
        ...searchInfo.value,
    });
    if (table.code === 0) {
        tableData.value = table.data.list.map((item) => {
            item.status = item.status == 1 ? "已確認" : "草稿";
            item.CreatedAt = item.CreatedAt ? formatDate(item.CreatedAt) : "";
            item.UpdatedAt = item.UpdatedAt ? formatDate(item.UpdatedAt) : "";
            // item.startFirstVersionCreatedAt = item.FirstCreatedAt ? formatDate(item.FirstCreatedAt) : "";
            // item.endFirstVersionCreatedAt = item.FirstCreatedAt ? formatDate(item.FirstCreatedAt) : "";
            return item;
        });
        pages.value.total = table.data.total;
        pages.value.page = table.data.page;
        pages.value.pageSize = table.data.pageSize;
    }
};

// ============== 表格控制部分结束 ===============

// 多选数据
const multipleSelection = ref([]);
// 多选
const updateMultipleSelection = (val) => {
    multipleSelection.value = val;
};

// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        deleteProductSpecFunc(row);
    });
};

// 多选删除
const onDelete = async () => {
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(async () => {
        const IDs = [];
        if (multipleSelection.value.length === 0) {
            ElMessage({
                type: "warning",
                message: "请选择要删除的数据",
            });
            return;
        }
        multipleSelection.value &&
            multipleSelection.value.map((item) => {
                IDs.push(item.ID);
            });
        const res = await deleteProductSpecByIds({ IDs });
        if (res.code === 0) {
            ElMessage({
                type: "success",
                message: "删除成功",
            });
            if (tableData.value.length === IDs.length && pages.value.page > 1) {
                pages.value.page--;
            }
            getTableData();
        }
    });
};

// 删除行
const deleteProductSpecFunc = async (row) => {
    const res = await deleteProductSpec({ ID: row.ID });
    if (res.code === 0) {
        ElMessage({
            type: "success",
            message: "删除成功",
        });
        if (tableData.value.length === 1 && pages.value.page > 1) {
            pages.value.page--;
        }
        getTableData();
    }
};

function detailSbuProjectsFunc(params) {
    console.log(params);
}

// 打开弹窗
const openDialog = () => {
    router.push({
        path: "/layout/productSpecAdd",
    });
};

function getDetails(datas, action) {
    if (!datas.ID) return;
    router.push({
        path: `/layout/productSpecAdd`,
        query: { styleNum: datas.styleNum, subTitle: "产" + datas.styleNum },
    });
}

// sub列表
const sbuOptions = ref([]);
// 获取sbu列表
const getSbuData = async (keyword) => {
    await getSbuDataList({ page: 1, pageSize: 100, sbuName: keyword }).then(
        (res) => {
            if (res.code === 0) {
                sbuOptions.value = res.data.list;
            }
        }
    );
};

// 复制产品规格
// 获取款式列表
const productStylesList = ref([]);
const remoteMethodProjectStyles = (keyword) => {
    getProductStylesQuickList(
        {
            page: 1,
            pageSize: 50,
            styleNum: keyword ? keyword : undefined,
            status: "1",
        },
        true
    ).then((res) => {
        if (res.code == 0) {
            productStylesList.value = res.data.list;
        }
    });
};
const toStyleNum = ref("");
const currentRow = ref({});
const copySpecificationFun = (row) => {
    copySpecificationShow.value = true;
    currentRow.value = row;
    toStyleNum.value = "";
};

// 复制产品规格
const replicateProductSpecFun = () => {
    if (!toStyleNum.value) {
        ElMessage({
            type: "warning",
            message: "请选择款式编号",
        });
        return;
    }
    let params = {
        fromStyleNum: currentRow.value.styleNum,
        toStyleNum: toStyleNum.value,
    };
    replicateProductSpec(params)
        .then((res) => {
            copySpecificationShow.value = false;
            if (res.code == 0) {
                router.push({
                    path: `/layout/productSpecAdd`,
                    query: { styleNum: toStyleNum.value, subTitle: "产" + toStyleNum.value },
                });
            }
        })
        .catch((err) => {
            copySpecificationShow.value = true;
        });
};

// 历史版本shou
const historyVisionShow = ref(false);
let historyList = ref([]); // 历史版本数据
// 历史版本
const historyVision = () => {
    historyList.value = [];
    let sel = multipleSelection.value[0];
    historyVisionShow.value = true;
    getProductSpecHistoryList({ styleNum: sel.styleNum }).then((res) => {
        if (res.code == 0) {
            historyList.value = res.data.list;
        }
    });
};
const rowDblclickFun = (row, column) => {
    historyVisionShow.value = false;
    if(row.ID == historyList.value[0].ID){
        router.push({
            path: `/layout/productSpecAdd`,
            query: { styleNum: row.styleNum, subTitle: "产" + row.styleNum },
        });
    }else{
        router.push({
            path: `/layout/productSpecAdd`,
            query: {
                styleNum: row.styleNum,
                subTitle: "产" + row.styleNum,
                isView: row.index === 0 ? 0 : 1,
                version: row.version,
            },
        });
    }
};

const tableRowClassName = ({ row, rowIndex }) => {
    row.index = rowIndex;
};

const handleInput = ()=>{
    toStyleNum.value = toStyleNum.value.replace(/\s/g, '')
    if(toStyleNum.value){
        toStyleNum.value = toStyleNum.value.toUpperCase();
    }
}

onMounted(() => {
    useDict("frameMaterials", "glassFrameCate", "sheetArcBend").then((d) => {
        let list = searchArr.value.map((item) => {
            if (item.prop == "frameMaterials") {
                item["selectList"] = [...d.frameMaterials];
            }
            if (item.prop == "glassFrameCate") {
                item["selectList"] = [...d.glassFrameCate];
            }
            if (item.prop == "sheetArcBend") {
                item["selectList"] = [...d.sheetArcBend];
            }
            return item;
        });
        searchArr.value = [];
        searchArr.value = [...list];
    });
});

watch(() => route.path, (newPath, oldPath) => {
//   console.log('路由已变更：', `从 ${oldPath} 到 ${newPath}`);
    if(newPath == '/layout/productSpec'){
        getTableData();
    }
},{immediate:true});
</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");
</style>
